import React, { useState, useEffect, useRef } from 'react'
import { getEmotionColors } from '../utils/emotionColors'

const PoemCard = ({ poem, emotion, userInput, generatedImage, isVisible, onCardFlip }) => {
  const [isFlipped, setIsFlipped] = useState(false)
  const [isAnimating, setIsAnimating] = useState(false)
  const [showContent, setShowContent] = useState(false)
  const cardRef = useRef(null)
  const emotionColors = getEmotionColors(emotion)

  // 抽卡动画效果
  useEffect(() => {
    if (isVisible && !isFlipped) {
      const timer = setTimeout(() => {
        setIsAnimating(true)
        // 先显示翻转动画
        setTimeout(() => {
          setIsFlipped(true)
          onCardFlip && onCardFlip()
        }, 800)
        // 再显示内容
        setTimeout(() => {
          setShowContent(true)
          setIsAnimating(false)
        }, 1600)
      }, 500)
      
      return () => clearTimeout(timer)
    }
  }, [isVisible, isFlipped, onCardFlip])

  // 卡片稀有度判断
  const getCardRarity = (emotion) => {
    const rarityMap = {
      '诗意盎然': { level: 'legendary', name: '传说', color: '#ff6b35', glow: '#ff6b35' },
      '喜而不狂': { level: 'epic', name: '史诗', color: '#a855f7', glow: '#a855f7' },
      '哀而不伤': { level: 'rare', name: '稀有', color: '#3b82f6', glow: '#3b82f6' },
      '思而不忧': { level: 'uncommon', name: '优秀', color: '#10b981', glow: '#10b981' },
      '淡然自若': { level: 'common', name: '普通', color: '#6b7280', glow: '#6b7280' }
    }
    return rarityMap[emotion] || rarityMap['淡然自若']
  }

  const rarity = getCardRarity(emotion)

  return (
    <div className="relative w-full max-w-md mx-auto perspective-1000">
      {/* 抽卡特效背景 */}
      {isAnimating && (
        <div className="absolute inset-0 z-0">
          {/* 光芒特效 */}
          <div 
            className="absolute inset-0 animate-pulse"
            style={{
              background: `radial-gradient(circle, ${rarity.glow}40 0%, transparent 70%)`,
              filter: 'blur(20px)'
            }}
          />
          
          {/* 粒子特效 */}
          {[...Array(20)].map((_, i) => (
            <div
              key={i}
              className="absolute w-2 h-2 rounded-full animate-ping"
              style={{
                left: `${Math.random() * 100}%`,
                top: `${Math.random() * 100}%`,
                backgroundColor: rarity.color,
                animationDelay: `${Math.random() * 2}s`,
                animationDuration: `${1 + Math.random()}s`
              }}
            />
          ))}
        </div>
      )}

      {/* 主卡片容器 */}
      <div 
        ref={cardRef}
        className={`relative w-full h-[600px] transition-all duration-1000 transform-style-preserve-3d ${
          isFlipped ? 'rotate-y-180' : ''
        } ${isAnimating ? 'scale-110' : 'scale-100'}`}
        style={{
          filter: isAnimating ? `drop-shadow(0 0 30px ${rarity.glow}80)` : 'none'
        }}
      >
        {/* 卡片背面 */}
        <div className="absolute inset-0 w-full h-full backface-hidden">
          <div 
            className="w-full h-full rounded-2xl border-4 relative overflow-hidden"
            style={{
              borderColor: rarity.color,
              background: `linear-gradient(135deg, ${rarity.color}20, ${rarity.color}40)`
            }}
          >
            {/* 卡背图案 */}
            <div className="absolute inset-0 opacity-30">
              <div 
                className="w-full h-full"
                style={{
                  backgroundImage: `
                    radial-gradient(circle at 25% 25%, ${rarity.color}40 0%, transparent 50%),
                    radial-gradient(circle at 75% 75%, ${rarity.color}30 0%, transparent 50%),
                    conic-gradient(from 0deg, ${rarity.color}20, transparent, ${rarity.color}20)
                  `,
                  backgroundSize: '100px 100px, 150px 150px, 200px 200px'
                }}
              />
            </div>
            
            {/* 卡背中心图标 */}
            <div className="absolute inset-0 flex items-center justify-center">
              <div 
                className="w-32 h-32 rounded-full border-4 flex items-center justify-center text-6xl"
                style={{ 
                  borderColor: rarity.color,
                  backgroundColor: `${rarity.color}20`,
                  color: rarity.color
                }}
              >
                🎴
              </div>
            </div>
            
            {/* 卡背装饰 */}
            <div className="absolute top-4 left-4 right-4 text-center">
              <div 
                className="text-lg font-bold px-4 py-2 rounded-full"
                style={{ 
                  backgroundColor: `${rarity.color}30`,
                  color: rarity.color
                }}
              >
                心语国韵
              </div>
            </div>
          </div>
        </div>

        {/* 卡片正面 */}
        <div className="absolute inset-0 w-full h-full backface-hidden rotate-y-180">
          <div 
            className="w-full h-full rounded-2xl border-4 relative overflow-hidden"
            style={{
              borderColor: rarity.color,
              boxShadow: `0 0 30px ${rarity.glow}40`
            }}
          >
            {/* 背景图片 - 采用与分享卡片同样的融合设计 */}
            {generatedImage?.success && (
              <div className="absolute inset-0">
                <img
                  src={generatedImage.imageUrl}
                  alt="诗意背景"
                  className="w-full h-full object-cover"
                  style={{
                    filter: 'brightness(0.85) contrast(1.1) saturate(1.2)', // 保持更多图片细节
                    opacity: 0.85 // 提高透明度，与分享卡片一致
                  }}
                />

                {/* 径向渐变遮罩 - 与分享卡片一致的融合效果 */}
                <div
                  className="absolute inset-0"
                  style={{
                    background: `
                      radial-gradient(
                        ellipse at center,
                        rgba(255, 255, 255, 0.1) 0%,
                        rgba(255, 255, 255, 0.3) 60%,
                        rgba(0, 0, 0, 0.6) 100%
                      )
                    `
                  }}
                />
              </div>
            )}

            {/* 稀有度标识 */}
            <div className="absolute top-4 right-4 z-10">
              <div
                className="px-3 py-1 rounded-full text-sm font-bold text-white shadow-lg ancient-title"
                style={{
                  backgroundColor: rarity.color,
                  boxShadow: `0 0 15px ${rarity.glow}60`,
                  fontFamily: '"Ma Shan Zheng", "STXinwei", serif',
                  letterSpacing: '0.15em',
                  background: `linear-gradient(45deg, ${rarity.color}, ${rarity.glow})`
                }}
              >
                {rarity.name}
              </div>
            </div>

            {/* 情绪标签 */}
            <div className="absolute top-4 left-4 z-10">
              <div
                className="px-4 py-2 rounded-full backdrop-blur-md border-2 text-white font-medium seal-effect"
                style={{
                  backgroundColor: `${rarity.color}90`,
                  borderColor: `${rarity.color}`,
                  fontFamily: '"Ma Shan Zheng", "STXinwei", serif',
                  letterSpacing: '0.2em'
                }}
              >
                {emotion}
              </div>
            </div>

            {/* 诗句内容区域 - 采用融合设计，去除大块背景 */}
            <div className="absolute inset-x-4 bottom-4 top-20 z-10">
              <div className="h-full flex flex-col justify-center">
                {/* 用户输入 - 精简设计 */}
                <div className="text-center mb-6">
                  <div
                    className={`inline-block px-4 py-2 rounded-full backdrop-blur-md transition-all duration-1000 ${
                      showContent ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-4'
                    }`}
                    style={{
                      backgroundColor: 'rgba(0, 0, 0, 0.3)',
                      border: `1px solid ${rarity.color}80`,
                      fontFamily: '"KaiTi", "楷体", serif',
                      letterSpacing: '0.08em',
                      color: 'white',
                      textShadow: '0 1px 3px rgba(0,0,0,0.5)'
                    }}
                  >
                    "{userInput.length > 25 ? userInput.substring(0, 25) + '...' : userInput}"
                  </div>
                </div>

                {/* 诗句主体 - 书法风格，每行单独背景 */}
                <div className="flex-1 flex items-center justify-center">
                  <div className="text-center space-y-3">
                    {poem.split('\n').map((line, index) => (
                      <div
                        key={index}
                        className={`relative transition-all duration-500 ${
                          showContent ? 'opacity-100 translate-x-0' : 'opacity-0 translate-x-4'
                        }`}
                        style={{
                          transitionDelay: `${index * 200}ms`
                        }}
                      >
                        {/* 每行诗句的半透明背景 */}
                        <div
                          className="absolute inset-0 rounded-lg backdrop-blur-sm"
                          style={{
                            backgroundColor: 'rgba(0, 0, 0, 0.2)',
                            transform: 'translateX(-10px) translateY(-5px)',
                            width: 'calc(100% + 20px)',
                            height: 'calc(100% + 10px)'
                          }}
                        />

                        {/* 诗句文字 */}
                        <div
                          className="relative text-2xl font-medium py-2 px-4"
                          style={{
                            fontFamily: '"KaiTi", "楷体", serif',
                            color: 'white',
                            textShadow: '0 2px 4px rgba(0,0,0,0.7), 0 0 8px rgba(0,0,0,0.3)',
                            letterSpacing: '0.1em'
                          }}
                        >
                          {line}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 底部装饰 */}
                <div className="text-center mt-4">
                  <div
                    className="inline-block px-4 py-1 rounded-full text-sm font-medium text-white brush-text"
                    style={{
                      backgroundColor: rarity.color,
                      fontFamily: '"Noto Serif SC", "KaiTi", serif',
                      letterSpacing: '0.1em'
                    }}
                  >
                    心语国韵 · {new Date().toLocaleDateString('zh-CN')}
                  </div>
                </div>
              </div>
            </div>

            {/* 卡片边框光效 */}
            <div 
              className="absolute inset-0 rounded-2xl pointer-events-none"
              style={{
                background: `linear-gradient(45deg, transparent, ${rarity.glow}30, transparent)`,
                animation: 'borderGlow 3s ease-in-out infinite'
              }}
            />
          </div>
        </div>
      </div>

      {/* 抽卡音效提示 */}
      {isAnimating && (
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-20">
          <div 
            className="text-4xl font-bold text-white animate-bounce"
            style={{ 
              textShadow: `0 0 20px ${rarity.glow}`,
              color: rarity.color
            }}
          >
            ✨ {rarity.name}卡片 ✨
          </div>
        </div>
      )}
    </div>
  )
}

export default PoemCard
